package com.my.algorithmlearning.leetcode;

import com.my.algorithmlearning.entity.TreeNode;
import org.springframework.util.Assert;

/**
 * @ClassName DiameterOfBinaryTree
 * @Description DiameterOfBinaryTree
 * @Author wanghaiwei
 * @Date 2023/1/29 14:19
 */
public class DiameterOfBinaryTree {
    private int maxDiameter;
    public int diameterOfBinaryTree(TreeNode root) {
        if (root == null) {
            return 0;
        }
        maxDiameter = 0;
        getDepth(root);
        return maxDiameter;
    }

    public int getDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int leftTreeDepth = getDepth(root.left);
        int rightTreeDepth = getDepth(root.right);
        if (leftTreeDepth + rightTreeDepth > maxDiameter) {
            maxDiameter = leftTreeDepth + rightTreeDepth;
        }
        return 1 + Math.max(leftTreeDepth, rightTreeDepth);
    }

    public int diameterOfBinaryTreeLowEfficient(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int currDiameter = getDepth(root.left) + getDepth(root.right);
        return Math.max(Math.max(diameterOfBinaryTreeLowEfficient(root.left), diameterOfBinaryTreeLowEfficient(root.right)), currDiameter);
    }

    public static void main(String[] args) {
        DiameterOfBinaryTree solution = new DiameterOfBinaryTree();
        TreeNode root1 = new TreeNode(new Integer[]{1,2,3,4,5});
        int result1 = solution.diameterOfBinaryTree(root1);
        Assert.isTrue(result1 == 3, "[1,2,3,4,5]解答错误，预期3，实际:"+ result1);

        TreeNode root2 = new TreeNode(new Integer[]{1,2});
        int result2 = solution.diameterOfBinaryTree(root2);
        Assert.isTrue(result2 == 1, "[1,2]解答错误，预期1，实际:"+ result2);

        TreeNode root3 = new TreeNode(new Integer[]{4,-7,-3,null,null,-9,-3,9,-7,-4,null,6,null,-6,-6,null,null,0,6,5,null,9,null,null,-1,-4,null,null,null,-2});
        int result3 = solution.diameterOfBinaryTree(root3);
        Assert.isTrue(result3 == 8, "[4,-7,-3,null,null,-9,-3,9,-7,-4,null,6,null,-6,-6,null,null,0,6,5,null,9,null,null,-1,-4,null,null,null,-2]解答错误，预期8，实际:"+ result3);
    }
}
